from ..extends.flask_sqlalchemy import db
import time
from flask import jsonify
from sqlalchemy import inspect, Column, Integer, String, Boolean


class BaseModel(db.Model):
    __abstract__ = True
    id = Column(Integer, primary_key=True, autoincrement=True)
    status = Column(Boolean, index=True, nullable=False, default=True, comment='状态')
    create_time = Column(
        Integer,
        index=True,
        nullable=False,
        default=time.time,
        comment='创建时间'
    )
    update_time = Column(
        Integer,
        index=True,
        nullable=False,
        default=time.time,
        comment='修改时间',
        onupdate=time.time
    )
    remark = Column(String(128), nullable=False, default='', comment='备注')

    @property
    def create_datetime(self):
        if self.create_time:
            return time.strftime('%Y-%m-%d %H:%M', time.localtime(self.create_time))
        return ''

    @property
    def update_datetime(self):
        if self.update_time:
            return time.strftime('%Y-%m-%d %H:%M', time.localtime(self.update_time))
        return ''

    @property
    def create_date(self):
        if self.create_time:
            return time.strftime('%Y-%m-%d', time.localtime(self.create_time))
        return ''

    def pk(self):
        return inspect(self).identity

    def to_json(self):
        json = dict()
        for k, v in self._fields:
            if hasattr(self, k):
                json[k] = v
        return jsonify(json)

    def set_fields(self, data):
        for key, value in data.items():
            if hasattr(self, key) and key != 'id':
                setattr(self, key, value)

    def from_dict(self, data):
        self.set_fields(data)
        return self
